#!/bin/bash
# 显示菜单选项

show_menu() {
    clear
    echo "====Linux多功能脚本 ===="
    echo "1. 查看系统基本信息"
    echo "2. 配置DDNS到腾讯云"
    echo "3. 配置私钥登录"
    echo "4. 禁用root登录"
    echo "5. 禁用IPV6"
    echo "6. 关闭SElinux"
    echo "7. CentOS更新内核版本到5.4.265"
    echo "8. 更换镜像源"
    echo "9. 安装docker,配置docker源"
    echo "q. 退出"
    echo "===================="
}

# 获取并显示系统信息
view_system_info() {
    hostname=$(hostname)
    system_name=$(cat /etc/os-release | grep "PRETTY_NAME" | cut -d "=" -f 2 | sed 's/"//g')
    system_version=$(cat /etc/os-release | grep "VERSION_ID" | cut -d "=" -f 2 | sed 's/"//g')
    kernel_version=$(uname -r)
    system_type=$(uname -m)
    ip_address=$(hostname -I | awk '{print $1}')
    cpu_model=$(cat /proc/cpuinfo | grep "model name" | head -1 | cut -d ":" -f 2 | sed 's/^[ \t]*//')
    cpu_cores=$(cat /proc/cpuinfo | grep "cpu cores" | head -1 | cut -d ":" -f 2 | sed 's/^[ \t]*//')
    machine_model=$(dmidecode -s system-product-name)
    system_time=$(date)
    summemory=$(free -h |grep "Mem:" | awk '{print $2}')
    freememory=$(free -h |grep "Mem:" | awk '{print $4}')
    usagememory=$(free -h |grep "Mem:" | awk '{print $3}')
    uptime=$(uptime | awk '{print $2" "$3" "$4" "$5}' | sed 's/,$//g')
    loadavg=$(uptime | awk '{print $9" "$10" "$11" "$12" "$13}')

    echo "主机名： $hostname"
    echo "系统名称： $system_name"
    echo "系统版本： $system_version"
    echo "内核版本： $kernel_version"
    echo "系统类型： $system_type"
    echo "本机IP地址： $ip_address"
    echo "CPU型号： $cpu_model"
    echo "CPU核数： $cpu_cores"
    echo "机器型号： $machine_model"
    echo "系统时间： $system_time"
    echo "总内存大小: $summemory"
    echo "已使用内存大小: $usagememory"
    echo "可使用内存大小: $freememory"
    echo "系统运行时间:   $uptime"
    echo "系统负载:  $loadavg"
    echo "开机启动的服务:"
    systemctl list-unit-files | grep enabled
    read -p "按任意键继续..."
}


ddns_dnspod() {
echo "======================================================脚本须知=========================================================="
echo "dnspod仅支持密钥登录，申请地址 https://console.dnspod.cn/account/token"
echo "不支持腾讯云API访问控制!!!"
echo "定时执行的方法   crontab -e 然后写入下面的内容，将日志文件写入到/var/log/ddns/ddns.log"
echo "*/1 * * * * bash -x /root/ddnsupdate.sh | while read line; do echo "$(date): $line"; done > /var/log/ddns/ddns.log 2>&1"
echo "arToken="你的密钥ID,你的密钥Token""
echo "domain="你的主域名""
echo "subdomain="你的子域""
echo "=====================================================脚本须知==========================================================="


echo -n "你的密钥ID,你的密钥Token > "
read arToken
echo -n "你的主域名 > "
read domain
echo -n "你的子域名 > "
read subdomain


arIpAddress() {
    curltest=$(which curl)
    if [ -z "$curltest" ] || [ ! -s "$(which curl)" ]; then
        curl -4 -L -k -s whatismyip.akamai.com | grep -E -o '([0-9]+\.){3}[0-9]+'
        #curl -4 -L -k -s ip.sb | grep -E -o '([0-9]+\.){3}[0-9]+'
        #curl -4 -k -s "http://members.3322.org/dyndns/getip" | grep -E -o '([0-9]+\.){3}[0-9]+'
        #curl -4 -k -s ip.6655.com/ip.aspx | grep -E -o '([0-9]+\.){3}[0-9]+'
        #curl -4 -k -s ip.3322.net | grep -E -o '([0-9]+\.){3}[0-9]+'
        #curl -4 -k -s api.myip.la | grep -E -o '([0-9]+\.){3}[0-9]+'
    else
        curl -4 -L -k -s whatismyip.akamai.com | grep -E -o '([0-9]+\.){3}[0-9]+'
        #wget --no-check-certificate --quiet --output-document=- "http://ip.sb" | grep -E -o '([0-9]+\.){3}[0-9]+'
        #wget --no-check-certificate --quiet --output-document=- "http://members.3322.org/dyndns/getip" | grep -E -o '([0-9]+\.){3}[0-9]+'
        #wget --no-check-certificate --quiet --output-document=- "ip.6655.com/ip.aspx" | grep -E -o '([0-9]+\.){3}[0-9]+'
        #wget --no-check-certificate --quiet --output-document=- "ip.3322.net" | grep -E -o '([0-9]+\.){3}[0-9]+'
        #wget --no-check-certificate --quiet --output-document=- "api.myip.la" | grep -E -o '([0-9]+\.){3}[0-9]+'

    fi
}

arIpAddress=$(arIpAddress)

arDdnsInfo() {
    local recordID recordIP

    # Get Record ID
    recordID=$(arApiPost "Record.List" "domain=$domain&sub_domain=$subdomain")
    recordID=$(echo $recordID | sed 's/.*\[{"id":"\([0-9]*\)".*/\1/')

    # Last IP
    recordIP=$(arApiPost "Record.Info" "domain=$domain&record_id=$recordID")
    recordIP=$(echo $recordIP | sed 's/.*,"value":"\([0-9\.]*\)".*/\1/')

    # Output IP
    case "$recordIP" in
    [1-9]*)
        echo $recordIP
        ;;
    *)
        echo "$recordIP"
        echo "Get Record Info Failed!"
        ;;
    esac
}

arApiPost() {
    local inter="https://dnsapi.cn/${1:?'Info.Version'}"
    local param="login_token=${arToken}&format=json&${2}"
    curl -s -k -X POST $inter -d "$param"
}

arDdnsUpdate() {
    local recordID recordRS recordCD recordIP myIP

    # Get Record ID
    recordID=$(arApiPost "Record.List" "domain=${domain}&sub_domain=${subdomain}")
    recordID=$(echo $recordID | sed 's/.*\[{"id":"\([0-9]*\)".*/\1/')

    # Update IP
    myIP=$(arIpAddress)
    recordRS=$(arApiPost "Record.Ddns" "domain=${domain}&record_id=${recordID}&sub_domain=${subdomain}&record_type=A&value=${myIP}&record_line=默认")
    recordCD=$(echo $recordRS | sed 's/.*{"code":"\([0-9]*\)".*/\1/')
    recordIP=$(echo $recordRS | sed 's/.*,"value":"\([0-9\.]*\)".*/\1/')

    # Output IP
    if [ "$recordIP" = "$myIP" ]; then
        if [ "$recordCD" = "1" ]; then
            echo $recordIP
        fi
        # Echo error message
        echo $recordRS | sed 's/.*,"message":"\([^"]*\)".*/\1/'
    else
        echo "Update Failed! Please check your network."
    fi
}

hostIP=$(arIpAddress)
lastIP=$(arDdnsInfo)

echo "Updating Domain: $subdomain.$domain"
echo "HostIP: ${hostIP}"
echo "LastIP: ${lastIP}"
if [ "$lastIP" != "$hostIP" ]; then

    case "$lastIP" in
    [1-9]*)
        postRS=$(arDdnsUpdate)
        echo "postRS: ${postRS}"
        echo "Domain A record has been updated!"
        ;;
    *)
        echo "Got LastIP Error! Stopped!"
        ;;
    esac

elif [ "$lastIP" == "$hostIP" ]; then
    echo "Last Domain A Record Is The Same as The Current IP!"
    echo "Skipped!"
else
    echo "ERROR!"
fi

}


secret_key_login() {
echo "======================================================脚本须知=========================================================="
echo "                                        公钥和私钥需要自己准备，生成方法可百度                                          "
echo "=====================================================脚本须知==========================================================="
# 输入公钥
echo -n "输入你的公钥 > "
read public_key

# 下载公钥文件
echo $public_key >> /root/.ssh/id_rsa.pub

# 备份 SSH 服务器配置文件
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

# 检测当前操作系统
if [ -f /etc/redhat-release ]; then
  # 启用公钥登录
  sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config

  # 设置公钥文件路径
  sed -i 's/#AuthorizedKeysFile/AuthorizedKeysFile/' /etc/ssh/sshd_config
  echo "AuthorizedKeysFile     .ssh/authorized_keys /root/.ssh/authorized_keys" >> /etc/ssh/sshd_config

  # 将公钥复制到 /root/.ssh/authorized_keys
  cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys

  # 设置正确的权限
  chmod 700 /root/.ssh
  chmod 600 /root/.ssh/authorized_keys

  # 重启 SSH 服务
  service sshd restart
elif [ -f /etc/debian_version ]; then
  # Debian 或 Ubuntu 系列操作系统
  
  # 启用公钥登录
  sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config

  # 设置公钥文件路径
  sed -i 's/#AuthorizedKeysFile/AuthorizedKeysFile/' /etc/ssh/sshd_config
  echo "AuthorizedKeysFile     .ssh/authorized_keys /root/.ssh/authorized_keys" >> /etc/ssh/sshd_config

  # 将公钥复制到 /root/.ssh/authorized_keys
  cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys

  # 设置正确的权限
  chmod 700 /root/.ssh
  chmod 600 /root/.ssh/authorized_keys

  # 重启 SSH 服务
  systemctl restart sshd
else
  echo "不支持的操作系统。"
  exit 1
fi
}


disable_root_remote_login() {
    sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
    service sshd restart
    echo "已禁用root远程登录"
}


disable_ipv6() {
    echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
    echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.conf
    sysctl -p
    echo "已禁用IPV6"
}


disable_SELinux() {
    sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
    echo "重启主机后生效"
}


Centos_Update_kernel() {
    # 导入GPG密钥
    rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
    # 安装elrepo仓库
    yum install -y https://www.elrepo.org/elrepo-release-7.el7.elrepo.noarch.rpm
    # 安装yum-plugin-fastestmirror插件
    yum install -y yum-plugin-fastestmirror
    # 安装内核
    yum --enablerepo=elrepo-kernel install kernel-lt-5.4.265-1.el7.elrepo.x86_64
    # 移除不需要的内核工具和头文件
    yum remove -y kernel-tools* kernel-headers*
    # 安装内核开发、文档、头文件、工具和工具库
    yum --enablerepo=elrepo-kernel install kernel-lt-devel-5.4.265-1.el7.elrepo.x86_64 \n    kernel-lt-doc-5.4.265-1.el7.elrepo.noarch \n    kernel-lt-headers-5.4.265-1.el7.elrepo.x86_64 \n    kernel-lt-tools-5.4.265-1.el7.elrepo.x86_64 \n    kernel-lt-tools-libs-5.4.265-1.el7.elrepo.x86_64 \n    kernel-lt-tools-libs-devel-5.4.265-1.el7.elrepo.x86_64 -y
    echo y
    # 设置默认启动内核为0
    grub2-set-default 0
    # 生成grub配置并重启系统
    # 判断内核版本并执行相应操作
    kernel_version=$(grubby --default-kernel)
    if [[ "$kernel_version" == "/boot/vmlinuz-5.4.265-1.el7.elrepo.x86_64" ]]; then
        echo "内核版本升级成功5.4.265"
        sleep = 5
        reboot
    else
        echo "内核版本未升级成功为5.4.265，请检查。"
    fi
}

ChangeMirrors() {
	source changemirrors.sh
}

install_docker() {
	source install_docker.sh
}

# 主菜单循环
show_menu
    read -p "请输入选项： " option
    case $option in
        1) view_system_info;;
        2) ddns_dnspod;;
        3) secret_key_login;;
        4) disable_root_remote_login;;
        5) disable_ipv6;;
        6) disable_SELinux;;
        7) Centos_Update_kernel;;
        8) ChangeMirrors;;
        9) install_docker;;
        q) exit;;
        *) echo "无效的选项";;
    esac

